// import 'dart:typed_data';
//
// import 'package:flutter/material.dart';
// import 'package:flutter/services.dart';
// import 'package:flutter_svg/flutter_svg.dart';
// import 'package:hixing_app/assets/r_img.dart';
// import 'package:hixing_app/utils/logs.dart';
// import 'package:hixing_app/views/test_view/svg_to_path/model/svg_model.dart';
// import 'package:path_drawing/path_drawing.dart';
// import 'dart:core';
//
// import 'dart:ui' as ui;
//
// class SvgToPath extends StatefulWidget {
//   @override
//   _SvgToPathState createState() => _SvgToPathState();
// }
//
// class _SvgToPathState extends State<SvgToPath> {
//   List<SvgModel> pathList = [];
//   late ui.Picture? _picture;
//
//   @override
//   void initState() {
//     // TODO: implement initState
//     getSvg();
//     super.initState();
//   }
//
//   Future<String> readSvgAssetToString(String assetPath) async {
//     try {
//       return await rootBundle.loadString(assetPath);
//     } catch (e) {
//       print('Failed to read SVG asset: $e');
//       return '';
//     }
//   }
//
//   List<String> extractPathTagValues(String svgString) {
//     // 匹配 p标签字符串
//     final regex = RegExp('<path\\s[^>]*[^>]*>');
//     final matches = regex.allMatches(svgString);
//     final paths = <String>[];
//     print(matches.first);
//     // for (final match in matches) {
//     //   paths.add(match.group(1)!);
//     // }
//     return paths;
//   }
//
//   List<String> extractDValues(String svgString) {
//     // 匹配 空格+d="开头的字符串，并且循环字符串内容到双引号或者单引号结束，然后再匹配一个单引号或者双引号结束的正则
//     final dRegex = RegExp('\\sd=["\']([^"\']*)["\']');
//
//     final matches = dRegex.allMatches(svgString);
//     final dValues = <String>[];
//     for (final match in matches) {
//       final dValue = match.group(1);
//       dValues.add(dValue!);
//     }
//     return dValues;
//   }
//
//   Future<void> getSvg() async {
//     // File svgFile = File(ImgR.imgBgMyFill);
//     String _svgString = await readSvgAssetToString(ImgR.imgBgMyFill);
//     print("${_svgString}");
//   }
//
//   Future<void> svgStringToPath() async {
//     // String _str = 'M150 0 L75 200 L225 200 Z';
//     String _svgString = await readSvgAssetToString(ImgR.imgBgPguinSVG);
//     // List<String> _svgPathList = [];
//     //获取字符串里面的pathtag
//     List<String> pathTagStrList = extractPathTagValues(_svgString);
//     print("path标签字符串：${pathTagStrList}");
//     // List<String> dStr = extractDValues(_svgString);
//
//     // List<ui.Path> arr = [];
//     // if (dStr.isNotEmpty) {
//     //   dStr.forEach((element) {
//     //     // 把m开头的字符串转化成path对象
//     //     arr.add(parseSvgPathData(element));
//     //   });
//     // setState(() {
//     //   pathList = arr;
//     // });
//     // }
//
//     // setState(() {
//     //   savePath = trianglePath;
//     // });
//     // 如何获取path，解析字符串，把指令都 写成枚举，然后截取字符串，判断指令的值，匹配相对应的path的方法;
//
//     // return path.path;
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(
//         title: Text('模板'),
//       ),
//       body: Column(
//         children: [
//           SvgPicture.asset(
//             ImgR.imgBgMyFill,
//             width: 100,
//             height: 100,
//           ),
//           pathList.isEmpty == null
//               ? const SizedBox.shrink()
//               : Container(
//                   margin: EdgeInsets.only(bottom: 10),
//                   width: 50,
//                   height: 50,
//                   child: CustomPaint(
//                     painter: MyCustomPainter(
//                       pathList: pathList!,
//                     ),
//                   ),
//                 ),
//           ElevatedButton(
//             onPressed: () {
//               svgStringToPath();
//             },
//             child: Text("svg的D路径转path对象"),
//           )
//         ],
//       ),
//     );
//   }
// }
//
// class MyCustomPainter extends CustomPainter {
//   MyCustomPainter({required this.pathList});
//
//   final List<SvgModel> pathList;
//
//   @override
//   void paint(Canvas canvas, Size size) {
//     Paint paint = Paint()..color = Colors.red;
//     // TODO: implement paint
//     // 缩放path
//     pathList.forEach((pathItem) {
//       canvas.drawPath(scalePath(pathItem.path, size), paint);
//     });
//   }
//
//   @override
//   bool shouldRepaint(covariant CustomPainter oldDelegate) {
//     // TODO: implement shouldRepaint
//     return false;
//   }
// }
//
// // 缩放path对象
// Path scalePath(ui.Path path, Size size) {
//   final bounds = path.getBounds();
//   final scaleX = size.width / bounds.width;
//   final scaleY = size.height / bounds.height;
//   final scale = scaleX < scaleY ? scaleX : scaleY;
//   final offsetX = (size.width - bounds.width * scale) / 2;
//   final offsetY = (size.height - bounds.height * scale) / 2;
//
//   final matrix = Float64List.fromList([
//     //
//     scale, 0, 0, 0,
//     0, scale, 0, 0,
//     0, 0, 1, 0,
//     offsetX, offsetY, 0, 1,
//   ]);
//
//   final scaledPath = path.transform(matrix);
//
//   return scaledPath;
// }
import 'dart:ui';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:hixing_app/assets/r_img.dart';
import 'package:vector_graphics/vector_graphics.dart';
import 'package:vector_graphics_compiler/vector_graphics_compiler.dart' as vg;
import 'package:vector_graphics/src/listener.dart';

const String svgString = '''
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 166 202">
  <defs>
    <linearGradient id="triangleGradient">
      <stop offset="20%" stop-color="#000000" stop-opacity=".55" />
      <stop offset="85%" stop-color="#616161" stop-opacity=".01" />
    </linearGradient>
    <linearGradient id="rectangleGradient" x1="0%" x2="0%" y1="0%" y2="100%">
      <stop offset="20%" stop-color="#000000" stop-opacity=".15" />
      <stop offset="85%" stop-color="#616161" stop-opacity=".01" />
    </linearGradient>
  </defs>
  <path fill="#42A5F5" fill-opacity=".8" d="M37.7 128.9 9.8 101 100.4 10.4 156.2 10.4" />
  <path fill="#42A5F5" fill-opacity=".8" d="M156.2 94 100.4 94 79.5 114.9 107.4 142.8" />
  <path fill="#0D47A1" d="M79.5 170.7 100.4 191.6 156.2 191.6 156.2 191.6 107.4 142.8" />
  <g transform="matrix(0.7071, -0.7071, 0.7071, 0.7071, -77.667, 98.057)">
    <rect width="39.4" height="39.4" x="59.8" y="123.1" fill="#42A5F5" />
    <rect width="39.4" height="5.5" x="59.8" y="162.5" fill="url(#rectangleGradient)" />
  </g>
  <path d="M79.5 170.7 120.9 156.4 107.4 142.8" fill="url(#triangleGradient)" />
</svg>
''';

class SvgToPath extends StatefulWidget {
  @override
  _SvgToPathState createState() => _SvgToPathState();
}

class _SvgToPathState extends State<SvgToPath> {
  PictureInfo? _pictureInfo;
  Size svgSize = Size(100, 100);

  Future<void> testSvg(BuildContext context) async {
    // final SvgTheme theme = getTheme(context);
    // Uint8List _svgList = vg
    //     .encodeSvg(
    //   xml: svgString,
    //   theme: theme.toVgTheme(),
    //   colorMapper: null,
    //   debugName: 'Svg loader',
    //   enableClippingOptimizer: false,
    //   enableMaskingOptimizer: false,
    //   enableOverdrawOptimizer: false,
    // );
    // print("svg的uint8list：${_svgList.length}${_svgList}");
    String svg1 = await rootBundle.loadString(ImgR.imgBgPguinSVG);
    SvgStringLoader _loader = SvgStringLoader(svg1);
    ByteData _bytes = await _loader.loadBytes(context);

    // final _PictureKey key =
    // _PictureKey(loaderKey, locale, textDirection, false);
    // Uint8List _loaderU8List=  _bytes.buffer.asUint8List();
    //  print("loader解析出来的数据111：${_loaderU8List.length},${_loaderU8List}");
    PictureInfo? _info = await bytesToPicture(_loader, _bytes);
    print("PictureInfo : ${_info}");
    if (_info != null) {
      svgSize = Size(200, 200);
      _pictureInfo = _info;
      setState(() {});
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    testSvg(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      children: [
        Container(
          color: Colors.black.withAlpha(120),
          child: SizedBox(
            width: svgSize.width,
            height: svgSize.height,
            child: CustomPaint(
              painter: MySvgPainter(pictureInfo: _pictureInfo, resize: svgSize),
            ),
          ),
        ),
        Container(
          color: Colors.red,
          child: SvgPicture.string(
            svgString,
            width: 100,
            height: 100,
          ),
        ),
        ElevatedButton(
          onPressed: () {
            testSvg(context);
          },
          child: Text("重新绘制svg"),
        ),
      ],
    ));
  }
}

class MySvgPainter extends CustomPainter {
  MySvgPainter({required this.pictureInfo, required this.resize});

  PictureInfo? pictureInfo;
  Size resize;

  @override
  void paint(Canvas canvas, Size size) {
    print("svg的size:${resize}");
    canvas.drawRect(
        Rect.fromCenter(center: Offset.zero, width: 200, height: 200), Paint());
    if (pictureInfo != null) {
      print("svg的size:${size}");
      canvas.save();
      canvas.scale(
        resize.width / pictureInfo!.size.width,
        resize.height / pictureInfo!.size.height,
      );
      // TODO: implement paint
      canvas.drawPicture(pictureInfo!.picture);
      canvas.restore();
    }
  }

  @override
  bool shouldRepaint(covariant MySvgPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return pictureInfo?.picture != oldDelegate.pictureInfo?.picture;
  }
}

void _handleError(Object error, StackTrace? stackTrace) {
  // setState(() {
  //   _error = error;
  //   _stackTrace = stackTrace;
  // });
}

Future<PictureInfo?> bytesToPicture(
    BytesLoader loader, ByteData byteData) async {
  PictureInfo _info = await decodeVectorGraphics(
    byteData,
    // 语言模块
    locale: null,
    // bool matchTextDirection = false,
    textDirection: TextDirection.ltr,
    //    this.allowDrawingOutsideViewBox = false,
    clipViewbox: false,
    loader: loader,
    onError: (Object error, StackTrace? stackTrace) {
      return _handleError(
        error,
        stackTrace,
      );
    },
  );
  return _info;
}

SvgTheme getTheme(BuildContext? context) {
  if (context != null) {
    final SvgTheme? defaultTheme = DefaultSvgTheme.of(context)?.theme;
    if (defaultTheme != null) {
      return defaultTheme;
    }
  }
  return const SvgTheme();
}
